package com.yunquan.ohana.ui.photos.item

import android.annotation.SuppressLint
import android.graphics.Bitmap
import androidx.databinding.ObservableField
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.ui.ItemViewModel
import com.yunquan.ohana.entity.PhotosEntity
import com.yunquan.ohana.ui.photos.PhotosViewModel
import java.util.concurrent.TimeUnit

class PhotosItemViewModel(viewModel: PhotosViewModel) : ItemViewModel<PhotosViewModel>(viewModel) {
    var data: PhotosEntity? = null
    val path = ObservableField<String>()
    val typeIndex = ObservableField<Int>()
    val duration = ObservableField<String>()
    val thumbnail = ObservableField<String>()

    val checked = ObservableField<Boolean>()
    val checkedIcon = ObservableField<Int>()

    val isSingleSelect = ObservableField(false)

    @SuppressLint("DefaultLocale")
    constructor(viewModel: PhotosViewModel, data: PhotosEntity) : this(viewModel) {
        this.isSingleSelect.set(viewModel.isSingleSelect.get())
        this.data = data
        this.path.set(data.path)
        this.typeIndex.set(if (data.type!!.contains("image")) 1 else 2)
        if (typeIndex.get() == 2) {
            val hours = TimeUnit.MILLISECONDS.toHours(data.duration ?: 0)
            val minutes = TimeUnit.MILLISECONDS.toMinutes(data.duration ?: 0) % 60
            val seconds = TimeUnit.MILLISECONDS.toSeconds(data.duration ?: 0) % 60
            if (seconds != 0L || minutes != 0L || hours != 0L) {
                this.duration.set(String.format("%02d:%02d:%02d", hours, minutes, seconds))
            }
            this.thumbnail.set(data.thumbnail)
        }
        checkChange(viewModel.checkedList.containsKey(data.id))
    }

    fun checkChange(isCheck: Boolean) {
        if (isCheck) {
            this.checked.set(true)
            this.checkedIcon.set(R.mipmap.ic_check_true)
        } else {
            this.checked.set(false)
            this.checkedIcon.set(R.mipmap.ic_check_false)
        }
    }

    val onCheckClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            if (data == null) return
            val checked = checked.get() ?: false
            val result = viewModel.onCheckChange(!checked, data!!)
            checkChange(result)
        }
    })

    val onItemClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            viewModel.onItemClick(this@PhotosItemViewModel)
        }
    })
}